package com.lianqi.emcpframework.core.generator;

import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @program emcp-framework
 * @ClassName RequestIDGenerator
 * @description: 客户端请求id标识生成器
 * @author: sky
 * @create: 2018/11/14 17:24
 */
public class RequestIDGenerator {

    final AtomicLong sequeceId = new AtomicLong(1);
    String hostName;
    static final String DEFAULT_HOST = "localhost";

    /**
     * 内部类 保证同步锁
     */
    static class InstanceHolder {
        static RequestIDGenerator idGenerator = new RequestIDGenerator();
    }

    /**
     * 构造函数
     * hostName 取machineName
     */
    private RequestIDGenerator(){
        try {
            this.hostName = java.net.InetAddress.getLocalHost().getHostName();

            int idx = this.hostName.indexOf(".");
            if (idx > 0){
                this.hostName = this.hostName.substring(0,idx);
            }
        } catch (UnknownHostException e) {
           this.hostName = DEFAULT_HOST;
        }
    }

    /**
     * 获取sington实例
     * @return
     */
    public static RequestIDGenerator getInstance(){
        return InstanceHolder.idGenerator;
    }

    /**
     * 获取请求ID
     * @return
     */
    public String nextId(){
        return this.hostName + "-" + sequeceId.getAndIncrement();
    }
}
